package com.checkCode.service.serviceImpl;

import com.checkCode.code.CheckCodeGenerator;
import com.checkCode.entity.dto.CheckCodeResultDto;
import com.checkCode.entity.vo.CheckCodeParamsVo;
import com.checkCode.keyName.KeyNameGenerator;
import com.checkCode.service.ICheckCodeService;
import com.checkCode.store.CodeStore;
import com.checkCode.strategy.CodeGeneratorStrategyHolder;
import lombok.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import static com.checkCode.constants.CheckCodeConstants.*;


/**
 * @author 大忽悠
 * @create 2023/2/9 21:01
 */
@Component
@RequiredArgsConstructor
public class CheckCodeServiceImpl implements ICheckCodeService {
    private final CodeGeneratorStrategyHolder codeGeneratorStrategyHolder;
    private final CodeStore codeStore;
    private final KeyNameGenerator keyNameGenerator;
    private final CheckCodeGenerator checkCodeGenerator;

    @Override
    public CheckCodeResultDto generate(CheckCodeParamsVo checkCodeParamsVo) {
        String code = checkCodeGenerator.generate(DEFAULT_CODE_LENGTH);
        String codeKey = keyNameGenerator.generator(DEFAULT_CHECK_CODE_PREFIX);
        CheckCodeResultDto checkCodeResultDto = codeGeneratorStrategyHolder.generate(checkCodeParamsVo,
                CodeInfo.builder().code(code).codeKey(codeKey).build());
        //验证码持久化存储
        codeStore.store(codeKey,code,DEFAULT_CODE_EXPIRE_TIME);
        return checkCodeResultDto;
    }

    @Override
    public Boolean verify(String key, String code) {
        //验证码key或者val为空
        if(!StringUtils.hasLength(key)||!StringUtils.hasLength(code)){
            return false;
        }
        String codeStoreVal = codeStore.load(key);
        if(!code.equalsIgnoreCase(codeStoreVal)){
            return false;
        }
        codeStore.remove(key);
        return true;
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    @Builder
    public static class CodeInfo{
        String codeKey;
        String code;
    }
}
